package org.keyroy.map.core.animation;

import java.util.ArrayList;
import java.util.List;

import org.keyroy.map.core.manages.Resource;
import org.keyroy.map.core.sprite.Sprite;
import org.keyroy.mapEditor.ui.beans.MapUtil;
import org.keyroy.util.tag.Tag;
import org.keyroy.util.tag.XmlObject;

public class Animation extends XmlObject {
	public String name;
	public List<Sprite> sprites = new ArrayList<Sprite>();
	private int index;

	public void add(Sprite sprite) {
		sprites.add(sprite);
	}

	public void add(Sprite[][] sprites) {
		for (int y = 0; y < sprites[0].length; y++) {
			for (int x = 0; x < sprites.length; x++) {
				if (sprites[x][y] != null) {
					add(sprites[x][y]);
				}
			}
		}
	}

	public void reset() {
		set(0);
	}

	public int set(int index) {
		int ID;
		if (index >= 0 && index < sprites.size()) {
			this.index = index;
			Sprite sprite = sprites.get(index);
			if (sprite != null) {
				ID = sprite.ID;
			} else {
				ID = Sprite.SPRITE_DELETE_ID;
			}
		} else {
			this.index = 0;
			ID = Sprite.SPRITE_DELETE_ID;
		}
		return ID;
	}

	public int next() {
		return set(index + 1);
	}

	@Override
	public void initTag(Tag tag) {
		tag.addParameter("name", name);
		String dataString = MapUtil.tiles2String(sprites);
		tag.addParameter("data", dataString, dataString != null);
	}

	@Override
	public void initObj(Tag tag) {
		name = tag.getParameterValue("name");
		String dataString = tag.getParameterValue("data");
		if (dataString != null) {
			MapUtil.string2Tiles(sprites, dataString);
		}
	}

}
